package com.cn.threadpool;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * FUN: 线程池代理类
 * 
 * @author sushy
 * @date 2016-3-23
 */
public class MyThreadPoolProxy {

	private static Map<String, MyThreadPool> threadPools = new ConcurrentHashMap<String, MyThreadPool>();

	/**
	 * 创建线程池
	 * 
	 * @param poolName
	 *            线程池名称
	 * @param corePoolSize
	 *            内核线程数
	 * @param timeOut
	 *            调用超时返回
	 * @return
	 */
	public static MyThreadPool createThreadPool(String poolName, int corePoolSize, long timeOut, boolean isCallerRuns) {
		// 繁忙时允许增加内核线程数一半的线程出，且不少于10
		int maximumPoolSize = corePoolSize + Math.max(corePoolSize / 2, 10);

		// 默认队列长度为两倍于内核线程数，且不小于10
		int maxQueueLength = Math.max(2 * corePoolSize, 10);

		// 线程空闲10秒，自动退出
		return MyThreadPoolProxy.createThreadPool(poolName, corePoolSize, maximumPoolSize, maxQueueLength, 10, timeOut,
				isCallerRuns);
	}

	/**
	 * 创建线程池
	 * 
	 * @param poolName
	 *            线程池名称
	 * @param corePoolSize
	 *            内核线程数
	 * @param maximumPoolSize
	 *            繁忙时最大线程数
	 * @param maxQueueLength
	 *            队列最大长度
	 * @param timeOut
	 *            调用超时返回
	 * @return
	 */
	public static MyThreadPool createThreadPool(String poolName, int corePoolSize, int maximumPoolSize,
			int maxQueueLength, long timeOut, boolean isCallerRuns) {
		// 线程空闲10秒，自动退出
		return MyThreadPoolProxy.createThreadPool(poolName, corePoolSize, maximumPoolSize, maxQueueLength, 10, timeOut,
				isCallerRuns);
	}

	/**
	 * 创建线程池
	 * 
	 * 
	 * @param poolName
	 *            线程池名称
	 * @param corePoolSize
	 *            内核线程数
	 * @param maximumPoolSize
	 *            繁忙时最大线程数
	 * @param maxQueueLength
	 *            队列最大长度
	 * @param keepAliveTime
	 *            线程空闲自动退出时长（秒），
	 * @param timeOut
	 *            调用超时返回
	 * @return
	 */
	public static MyThreadPool createThreadPool(String poolName, int corePoolSize, int maximumPoolSize,
			int maxQueueLength, int keepAliveTime, long timeOut, boolean isCallerRuns) {
		MyThreadPool threadPool = new MyThreadPool(poolName, corePoolSize, maximumPoolSize, maxQueueLength,
				keepAliveTime, timeOut, isCallerRuns);
		threadPools.put(poolName, threadPool);
		return threadPool;
	}

	public static MyThreadPool getThreadPool(String poolName) {
		return threadPools.get(poolName);
	}

	public static Map<String, MyThreadPool> getThreadPools() {
		return threadPools;
	}

}
